import {defineStore} from 'pinia'
import router from '@/router'
import {ref} from 'vue'
import {userLogin} from "@/api/login"
import type {ILoginInf} from "@/interface/loginInf.ts";

// 定义用户信息的类型
interface UserInfo {
  username: string
  name: string
  avatar: string
  token: string
}

// 使用组合式 API 风格定义 store
export const useUserStore = defineStore('main', () => {
  // 定义状态
  const userInfo = ref<UserInfo>(
    localStorage.getItem('userInfo')
      ? JSON.parse(localStorage.getItem('userInfo')!)
      : {username: '', name: '', avatar: '', token: ''},
  )

  const token = ref<string>(localStorage.getItem('token') || '')

  // 定义 actions
  const login = async (data: ILoginInf) => {
    userLogin(data)
      .then((response) => {
        if (response) {
          return {
            code: 201,
            data: response
          }
        }
      })
      .catch((error) => {
        return {
          code: 202,
          data: error
        }
      })

  }

  const loginIn = async (data: UserInfo) => {
    userInfo.value = data
    localStorage.setItem('userInfo', JSON.stringify(data))
    localStorage.setItem('token', data.token)
    await router.push({path: '/'})
  }

  return {
    userInfo,
    token,
    login,
    loginIn,
  }
})
